# -*- coding: utf-8 -*-
import sys
sys.path.append('/home/vv/codes/Jupiter/web/webshow/gen-py')
from django.shortcuts import get_object_or_404,render_to_response
from django.core.paginator import PageNotAnInteger, Paginator, InvalidPage, EmptyPage

from news import newsService
from news.ttypes import *

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
#from thrift.protocol import TCompactProtocol
from thrift.protocol import TBinaryProtocol



def index(request):
    return render_to_response('index.html')

def introduce(request):
    return render_to_response('introduce.html')

def do_page(r,items,pagenum=10):
    after_range_num = 5
    befor_range_num = 4
    try:
        page = int(r.GET.get("page",1))
        if page < 1:
            page = 1
    except ValueError:
        page = 1
    paginator = Paginator(items,pagenum)
    try:
        results_list = paginator.page(page)
    except(EmptyPage,InvalidPage,PageNotAnInteger):
        results_list = paginator.page(paginator.num_pages)
    if page >= after_range_num:
        page_range = paginator.page_range[page-after_range_num:page+befor_range_num]
    else:
        page_range = paginator.page_range[0:int(page)+befor_range_num]
    return (results_list,page_range)

def search(request):
    query = request.GET.get('q','')
    show_num  = 100
    transport = TSocket.TSocket('localhost', 19091) # TODO: the server
    transport = TTransport.TBufferedTransport(transport)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = newsService.Client(protocol)
    transport.open()
    result=client.search(query.encode('gbk'),show_num)
    total_sum = result.total_sum
    show_num = result.show_num
    for item in result.show_result:
        item.title = item.title.decode('gbk').encode('utf-8')
    show_result = result.show_result
    
    transport.close()
    (results_list,page_range) = do_page(request,show_result,20);
    return render_to_response('search_result.html',{'result':results_list,
                                                    'query':query,
                                                    'total_num':total_sum,
                                                    'show_num':show_num,
                                                    'page_range':page_range})
